package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ListHolder;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.adapter.DepartmentListAdapter;
import library.and.xps.com.step.adapter.DepartmentsAdapterInTeamManagerDailog;
import library.and.xps.com.step.adapter.MemberListAdapter;
import library.and.xps.com.step.m.model.MemberInDepartment;
import library.and.xps.com.step.m.model.MoveMember;
import library.and.xps.com.step.m.model.TeamManager;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.CommonUtils;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseActivity;

public class DepartManageActivity extends BaseActivity {
    ListView lv_member;
    ListView lv_department;
    TextView tv_title;

    MemberListAdapter memberListAdapter;
    DepartmentListAdapter departmentListAdapter;

    MemberInDepartment memberInDepartment;
    TeamManager teamManager;
    String MemberId;

    @Override
    protected int getLayout() {
        return R.layout.activity_department_manage;
    }

    @Override
    protected void setData() {
        memberListAdapter = new MemberListAdapter(this);
        departmentListAdapter = new DepartmentListAdapter(this);
        lv_department.setAdapter(departmentListAdapter);
        lv_member.setAdapter(memberListAdapter);
        lv_member.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        lv_department.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<TeamManager.ListBean> data = ((DepartmentListAdapter) parent.getAdapter()).getData();
                Intent i = new Intent(DepartManageActivity.this, DepartmentDetailActivity.class);
                i.putExtra("department_click", data.get(position));
                startActivity(i);
            }
        });
        getUserDepartments();

    }

    /**
     * 获取部门列表
     */
    void getUserDepartments() {
        if (getUser() == null) return;
        String data = URLConstants.TEAM.ManageDepartment + "?userid=" + getUser().getUserid() + "&teamid=" + getUser().getTeams().get(0).getTId();
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                teamManager = new Gson().fromJson(response.getBody(), TeamManager.class);
                if(!TextUtils.isEmpty(teamManager.getObj())){
                    List<TeamManager.ListBean> list = teamManager.getList();
                    departmentListAdapter.setData(list);
                    CommonUtils.resetListViewHeight(lv_department);

                    getUsersInTeam(teamManager.getObj());
                }
            }

            @Override
            public void onStart() {
                showDialogNoCancel();
            }
        }, "");
    }

    void getUsersInTeam(String departmentId) {
        if (getUser() == null) return;
        String data = URLConstants.TEAM.ManageDepartmentUsers + "?userid=" + getUser().getUserid() + "&departmentid=" + departmentId;
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                memberInDepartment = new Gson().fromJson(response.getBody(), MemberInDepartment.class);
                if (HttpResponsHelper.SuccessResponce(memberInDepartment)) {
                    List<MemberInDepartment.ListBean> list = memberInDepartment.getList();
                    memberListAdapter.setData(list);
                    CommonUtils.resetListViewHeight(lv_member);
                }
            }

            @Override
            public void onStart() {
                showDialogNoCancel();
            }
        }, "");
    }

    /**
     * 接收从memberListAdapter里发送的 成员点击信息
     *
     * @see MemberListAdapter
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(String memberId) {
        MemberId = memberId;
        showdialog("将成员移动到:");
    }

    void showdialog(String hintText) {
        ViewHolder headerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.header, null));
        View headerView = headerViewHolder.getInflatedView();

        ((TextView) headerView.findViewById(R.id.tv_hint)).setText(hintText);
        DialogPlus dialog = DialogPlus.newDialog(this)
                .setContentHolder(new ListHolder())
                .setGravity(Gravity.CENTER)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        TeamManager.ListBean department = (TeamManager.ListBean) item;
                        moveMember(department.getDepartmentid() + "");
                        dialog.dismiss();
                    }
                })
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .setAdapter(new DepartmentsAdapterInTeamManagerDailog(this, teamManager.getList()))
                .setExpanded(true, 700)
                .setHeader(headerView)
                .create();
        dialog.show();
    }

    //移动成员
    void moveMember(String newDepartId) {
        String data = URLConstants.TEAM.MoveMember + "?userid=" + MemberId + "&olddeptid=" + teamManager.getObj() + "&newdeptid=" + newDepartId;

        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                MoveMember moveMember = new Gson().fromJson(response.getBody(), MoveMember.class);
                if (HttpResponsHelper.SuccessResponce(moveMember)) {
                    JUtils.Toast("成员已移动");
                    getUserDepartments();
                } else {
                    JUtils.Toast("移动成员失败");
                }
            }

            @Override
            public void onStart() {
                showDialogNoCancel();
            }
        }, "");
    }

    @Override
    protected void init() {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        lv_department = r2v(R.id.lv_department);
        lv_member = r2v(R.id.lv_member);
        r2v(R.id.actionbar_iv_back).setOnClickListener(this);

        TextView tv_actionbarRight = r2v(R.id.actionbar_tv_right);
        tv_actionbarRight.setVisibility(View.VISIBLE);
        tv_actionbarRight.setText("添加部门");
        tv_actionbarRight.setTextColor(R.color.colorPrimary);
        tv_actionbarRight.setOnClickListener(this);

        tv_title = r2v(R.id.actionbar_tv_title);
        tv_title.setText("部门管理");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        setResult(0);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.actionbar_tv_right:
                Intent intent = new Intent(this,CreateSubdepartmentActivity.class);
                intent.putExtra("defaultDepartmentId",teamManager.getObj());
                startActivityForResult(intent,0);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getUserDepartments();

    }
}
